<template>
  <div class="medicine-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>药品信息管理</h2>
          <el-button type="primary" @click="openMedicineDialog()">新增药品</el-button>
        </div>
      </template>

      <el-table :data="medicineList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="medicineName" label="药品名称"></el-table-column>
        <el-table-column prop="description" label="药品描述"></el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">¥{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openMedicineDialog(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="deleteMedicine(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </el-card>

    <!-- 药品编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑药品' : '新增药品'" width="50%">
      <el-form :model="medicineForm" label-width="100px">
        <el-form-item label="药品名称">
          <el-input v-model="medicineForm.medicineName" placeholder="请输入药品名称"></el-input>
        </el-form-item>

        <el-form-item label="药品描述">
          <el-input
            v-model="medicineForm.description"
            type="textarea"
            placeholder="请输入药品描述"
          ></el-input>
        </el-form-item>

        <el-form-item label="价格">
          <el-input v-model="medicineForm.price"></el-input>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="medicineForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMedicine">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listMedicine, getMedicine, addMedicine, updateMedicine, delMedicine } from '@/api/medicine'
import { listCategory } from '@/api/category'

// 药品列表
const medicineList = ref([])

// 分类列表
const categoryList = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 药品表单
const medicineForm = reactive({
  id: null,
  medicineName: '',
  description: '',
  price: 0,
  categoryId: null,
})

// 获取药品列表
const getMedicineList = async () => {
  try {
    const res = await listMedicine()

    // 获取分类列表
    const categoryRes = await listCategory()
    const categoryMap = {}
    categoryRes.data.forEach((category) => {
      categoryMap[category.id] = category.categoryName
    })

    // 将分类名称添加到药品信息中
    medicineList.value = res.data.map((medicine) => ({
      ...medicine,
      categoryName: categoryMap[medicine.categoryId] || '未分类',
    }))

    total.value = res.total || 0
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await listCategory()
    categoryList.value = res.data || []
  } catch (error) {
    console.error('获取分类列表失败', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 打开药品对话框
const openMedicineDialog = (medicine) => {
  if (medicine) {
    // 编辑模式
    isEdit.value = true
    Object.assign(medicineForm, medicine)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(medicineForm, {
      id: null,
      medicineName: '',
      description: '',
      price: 0,
      categoryId: null,
    })
  }

  dialogVisible.value = true
}

// 保存药品
const saveMedicine = async () => {
  try {
    if (isEdit.value) {
      // 编辑药品
      await updateMedicine(medicineForm)
      ElMessage.success('药品更新成功')
    } else {
      // 新增药品
      await addMedicine(medicineForm)
      ElMessage.success('药品添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新药品列表
    getMedicineList()
  } catch (error) {
    console.error('保存药品失败', error)
    ElMessage.error('保存药品失败')
  }
}

// 删除药品
const deleteMedicine = (medicine) => {
  ElMessageBox.confirm(`确定要删除药品 ${medicine.medicineName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delMedicine(medicine.id)
        ElMessage.success('药品删除成功')
        getMedicineList()
      } catch (error) {
        console.error('删除药品失败', error)
        ElMessage.error('删除药品失败')
      }
    })
    .catch(() => {})
}

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  getMedicineList()
}

// 初始化
onMounted(() => {
  getCategoryList()
  getMedicineList()
})
</script>
